import { Asset, AssetManager, assetManager, __private } from "cc";
import { Logger } from "../log/Logger";

export class LoaderBundle{
    /**
     * 当前loade是否加载
     */
    public isUse:boolean=false
    public path:string
    /** bundle数据 */
    public bundle:AssetManager.Bundle
    /**
     * 传递参数
     */
    public params:any;
    
    public clear(){
        this.isUse=false;
        this.path=null;
        this.bundle=null
        this.params=null
    }
    /**
     * 加载bundle 资源
     * @param path 
     * @param params 
     * @param progress 
     * @param finish 
     */
    public loadBundle(path:string,params:any,progress:(prv: number, total: number, item: LoaderBundle)=>void,finish:(loader:LoaderBundle)=>void){
        this.path=path;
        this.params=params;
        let version:any = params && params.version ? params.version : null;

        assetManager.loadBundle(path,version,(error:Error,data:AssetManager.Bundle)=>{
            if(!error){
                this.bundle=data
                this.bundle.loadDir("./",(finished: number, total: number, item: AssetManager.RequestItem)=>{
                    const prv:number = parseFloat((finished / total).toFixed(2))
                    progress && progress(prv,total,this)
                },(error1:Error,data1:any)=>{
                    if(!error1)finish && finish(this)
                })
            }else{
                finish && finish(null)
            }
        })
    }
    /**
     * 将bundle 包中的资源加载出来
     * @param path 
     * @param type 
     * @returns 
     */
    public load<T extends Asset>(path:string,type:{new():T}):Promise<T>{
        return new Promise(resolve=>{
            if(this.bundle){
                this.bundle.load(path,type,(err:Error,data:T)=>{
                    !err && resolve(data)
                    err && console.error(err)
                })
            }else{
                Logger.warn("资源【"+path+"】错误")
                resolve(null);
            }
        })
    }

}